let Ztip = {}
let showZtip = false
let ztipVM = null

Ztip.install = function(Vue) {
    Vue.prototype.$ztip = function(tips, options) {
        let opt = {
            type: 'info',
            duration: '2500',
            width: '300px'
        }

        let titleObject = {
            success: '成功',
            error: '错误',
            warning: '警告',
            info: '信息'
        }
        for (let property in options) {
            opt[property] = options[property]
        }
        let curType = options.type ? options.type : opt.type
        let style = options.width ? 'style="width:' + options.width + '"' : 'style="width:' + opt.width + '"'
        let tmp = '<div id="z-tip" v-show="show" class="z-tip"><div :class="type" class="z-tip-wrap"' + style + '><div class="z-tip-title"><span class="z-icon" :class="icon"></span><span class="z-tip-text">{{title}}</span></div><div class="z-tip-content">{{tip}}</div><i class="z-tip-close z-icon-close" @click="hide"></i></div></div>'

        if (showZtip) {
            return
        }
        if (!ztipVM) {
            // 创建构造器
            let ZTpl = Vue.extend({
                data: function() {
                    return {
                        show: showZtip,
                        tip: tips,
                        type: 'z-tip-' + curType,
                        icon: 'z-icon-' + curType,
                        title: titleObject[curType]
                    }
                },
                template: tmp,
                methods: {
                    hide() {
                        hideDom()
                    }
                }
            })

            ztipVM = new ZTpl() // 创建实例

            let tpl = ztipVM.$mount().$el // 挂载到一个元素上

            document.body.appendChild(tpl)
        }

        ztipVM.type = 'z-tip-' + curType
        ztipVM.tip = tips
        ztipVM.show = showZtip = true
        ztipVM.icon = 'z-icon-' + curType
        ztipVM.title = titleObject[curType]

        // 延时操作

        let timer = setTimeout(function() {
            delectDom()
            clearTimeout(timer)
        }, opt.duration)

        // 删除节点
        let delectDom = function() {
            ztipVM.show = showZtip = false
            let ztipName = document.getElementById('z-tip')
            document.body.removeChild(ztipName)
            ztipVM = null
        }

        // 与Vue中的交互
        let hideDom = function() {
            clearTimeout(timer)
            delectDom()
        }
    }
}

module.exports = Ztip